<?php
namespace app\model;
use think\Model;
use think\facade\Db;
class Copywriter extends Model{

    public function list($p){
        if(isset($p['title']) && !empty($p['title'])){
            $wh[] = ['w.title','like','%'.$p['title'].'%'];
        }
        if(isset($p['label_id']) && !empty($p['label_id'])){
            $wh[] = ['w.label_id','like','%'.$p['label_id'].'%'];
        }
        if(isset($p['author_id']) && !empty($p['author_id'])){
            $wh[] = ['w.author_id','=',$p['author_id']];
        }
        $wh[] = ['w.delete_time','=',null];
        
        $arr['list'] = $this->alias('w')
        ->field('w.*,a.name author')
        ->join('copywriter_author a','a.id = w.author_id','LEFT')
        ->where($wh)
        ->order('w.create_time desc')->page($p['page'],$p['limit'])->select();
        foreach ($arr['list'] as $k=>$v){
            $arr['list'][$k]['labels'] = $this->labels($v['label_id']);
        }
        $arr['cnt'] = $this->alias('w')->where($wh)->count('w.id');
        return $arr;
    }

    // 获取所有的标签
    function labels($label_id){
        $w[] = ['id','in',$label_id];
        $r = Db::name('copywriter_label')->where($w)->column('name');
        $r = implode(',',$r);
        return $r;
    }

    // 添加
    public function add($data){
        $validate = \think\facade\Validate::rule([
            'title|标题'  => 'require',
            'author_id|作者'  => 'require',
            'platform|平台'  => 'require',
            'label_id|标签'  => 'require',
            'describe|描述'  => 'require',
            'content|内容'  => 'require'
        ]);
    
        if(!$validate->check($data)){
            // 验证失败 输出错误信息
            return $validate->getError();
        }else{
            
            try {
                $this->save($data);
                return true;
            } catch (\Exception $e) {
                
                return $e->getMessage();
            }
        }
    }
    //修改
    public function get_save($data){
        $validate = \think\facade\Validate::rule([
            'title|标题'  => 'require',
            'author_id|作者'  => 'require',
            'platform|平台'  => 'require',
            'label_id|标签'  => 'require',
            'describe|描述'  => 'require',
            'content|内容'  => 'require'
        ]);
    
        if(!$validate->check($data)){
            // 验证失败 输出错误信息
            return $validate->getError();
        }else{
            try {
                $this->update($data);
                return true;
            } catch (\Exception $e) {
                
                return $e->getMessage();
            }
        }

    }


}